package com.yunhe.dtu.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class DingDingUtil {
    private static Logger log = LoggerFactory.getLogger(DingDingUtil.class);

    private  static String dingDingToken="https://oapi.dingtalk.com/robot/send?access_token=1f5abe9c533e8c081c0eab8268418af39f468b06226ddc96cd8f471451a502e1";
    private static String secret = "SEC04511d9dbe5d079f55502fa278bacea6a2206d4dea13df2ed062195bd19042ca";

    public static void send(String message) {
        try {
            Long timestamp = System.currentTimeMillis();
            dingDingToken +="&timestamp="+timestamp;
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
            dingDingToken +="&sign="+sign;

            // 请求的JSON数据，这里我用map在工具类里转成json格式
            Map<String,Object> json=new HashMap();
            json.put("msgtype","text");

            Map<String,Object> text=new HashMap();
            text.put("content",message);
            json.put("text",text);

            // 发送post请求
            SendHttps.sendPostByMap(dingDingToken, json);
        } catch (Exception e){
            log.error("发送钉钉消息异常");
        }

    }
}
